<?php
(!defined('IN_SYSTEM') || !defined('ADMIN_PRE')) && exit('Access Denied!');

if(!ican("systheme")){
 msg('对不起，你没有权限执行本操作！');
}

$f = isset($_REQUEST['f'])?$_REQUEST['f']:'index';

if ($f == 'index') {

	$theme_root = BASE_ROOT.'themes/';

	$result = read_dir($theme_root);

	$cur_theme = $_G['settings']['theme'];

	$themes = array();
	foreach ($result as $dir) {
		$dir = str_replace($theme_root, '', $dir);
		if(substr($dir['directory'],0,1) == '.') continue;
		$themes[$dir]['directory'] = $dir;
		$themes[$dir]['path'] = $theme_root.$dir.'/';
		$infofile = $themes[$dir]['path'].'info.xml';
		if ( file_exists($infofile) ) {
			$info = parse_theme_info($infofile);
			$themes[$dir] = array_merge($themes[$dir], $info);
		}
	}
	include admintemplate('theme');

} elseif ( $f == 'settheme' ) {

	$theme = check_str(getGP('theme'));
	if (is_dir(BASE_ROOT.'themes/'.$theme)) {
		if ($_G['db']->fetch_one_array("SELECT * FROM ".DB_PREFIX."settings WHERE `type` = '' AND `name` = 'theme'")) {
			$_G['db']->query("UPDATE ".DB_PREFIX."settings SET `value` = '$theme' WHERE `type` = '' AND `name` = 'theme'");
		} else {
			$_G['db']->query("INSERT INTO ".DB_PREFIX."settings (`name`, `value`, `type`) VALUES ('theme', '$theme', '')");
		}
		recache('settings');
		remove_dir(CACHE_ROOT.'./pages');
		remove_dir(CACHE_ROOT.'./templates');
		msg('设置成功','admin.php?m=theme');
	} else {
		msg('不存在该主题！','admin.php?m=theme');
	}
}

function parse_theme_info($file) {
	$fp = fopen($file, 'rb');
	$content = fread($fp, filesize($file));
	preg_match_all('/<name>(.+?)<\/name>/is',$content, $name);
	preg_match_all('/<author>(.*?)<\/author>/is',$content, $author);
	preg_match_all('/<version>(.*?)<\/version>/is',$content, $version);
	preg_match_all('/<pubdate>(.*?)<\/pubdate>/is',$content, $pubdate);
	preg_match_all('/<homepage>(.*?)<\/homepage>/is',$content, $homepage);
	preg_match_all('/<thumb>(.*?)<\/thumb>/is',$content, $thumb);
	preg_match_all('/<intro>(.*?)<\/intro>/is',$content, $intro);
	$info = array(
		'name' => $name[1][0],
		'author' => $author[1][0],
		'version' => $version[1][0],
		'pubdate' => $pubdate[1][0],
		'homepage' => $homepage[1][0],
		'thumb' => $thumb[1][0],
		'intro' => $intro[1][0],
	);
	return $info;
}
?>